package com.uatair.common.utils.ip;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.uatair.common.config.RuoYiConfig;
import com.uatair.common.constant.Constants;
import com.uatair.common.utils.StringUtils;
import com.uatair.common.utils.http.HttpUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取地址类
 * 
 * @author uatair
 */
public class AddressUtils
{
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    public static final String UNKNOWN = "XX XX";

    public static String getRealAddressByIP(String ip)
    {
        // 内网不查询
        if (IpUtils.internalIp(ip))
        {
            return "内网IP";
        }
        if (RuoYiConfig.isAddressEnabled())
        {
            try
            {
                String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", Constants.GBK);
                if (StringUtils.isEmpty(rspStr))
                {
                    log.error("获取地理位置异常 {}", ip);
                    return UNKNOWN;
                }
                JSONObject obj = JSON.parseObject(rspStr);
                String region = obj.getString("pro");
                String city = obj.getString("city");
                return String.format("%s %s", region, city);
            }
            catch (Exception e)
            {
                log.error("获取地理位置异常 {}", ip);
            }
        }
        return UNKNOWN;
    }

    /**
     * 解析中国行政区划地址
     * @param address 完整地址字符串
     * @return 包含各级行政区划的Map
     */
    public static Map<String, String> parseChineseAddress(String address) {
        Map<String, String> map = new HashMap<>();
        if (address == null || address.trim().isEmpty()) {
            return map;
        }

        // 正则表达式匹配各级行政区划
        String regex = "(?<province>[^省]+自治区|.*?省|.*?行政区|.*?市)(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)(?<county>[^县]+县|.*?区|.*?市|.*?旗|.*?海域|.*?岛)?(?<town>[^区]+街道|.*?镇|.*?乡|.*?民族乡|.*?苏木|.*?岛)?";
        Matcher matcher = Pattern.compile(regex).matcher(address);

        if (matcher.find()) {
            map.put("province", matcher.group("province"));
            map.put("city", matcher.group("city"));

            // 处理可能为null的区县和乡镇
            String county = matcher.group("county");
            if (county != null && !county.equals(matcher.group("city"))) {
                map.put("country", county); // 注意：标准字段名应为"county"
            } else {
                map.put("country", "");
            }

            String town = matcher.group("town");
            map.put("town", town != null ? town : "");
        }

        return map;
    }
}
